<template>
  <view class="container">
    <!-- 农作物基本信息 -->
    <view class="crop-info" v-if="crop">
      <view class="crop-header">
        <!-- 添加编辑按钮 -->
        <view class="edit-btn" @tap="editCrop">
          <uni-icons type="compose" size="18" color="#4CAF50"></uni-icons>
          <text>编辑</text>
        </view>
        
        <view class="crop-image">
          <image 
            :src="crop.image || '/static/images/default-crop.png'" 
            mode="aspectFill"
          ></image>
        </view>
        
        <view class="crop-title">
          <text class="crop-name">{{ crop.name }}</text>
          <view class="crop-status" :class="getStatusClass(crop.status)">
            <text>{{ getStatusText(crop.status) }}</text>
          </view>
        </view>
        
        <view class="crop-type">
          <text>{{ crop.crop_type }} · {{ crop.variety || '未知品种' }}</text>
        </view>
      </view>
      
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">种植位置</text>
          <text class="info-value">{{ crop.location }}</text>
        </view>
        
        <view class="info-item">
          <text class="info-label">种植日期</text>
          <text class="info-value">{{ formatDate(crop.plant_date) }}</text>
        </view>
        
        <view class="info-item" v-if="crop.area">
          <text class="info-label">种植面积</text>
          <text class="info-value">{{ crop.area }} 平方米</text>
        </view>
        
        <view class="info-item" v-if="crop.harvest_date">
          <text class="info-label">收获日期</text>
          <text class="info-value">{{ formatDate(crop.harvest_date) }}</text>
        </view>
        
        <view class="info-item" v-if="crop.description">
          <text class="info-label">描述</text>
          <text class="info-value">{{ crop.description }}</text>
        </view>
      </view>
    </view>
    
    <!-- 生长记录 -->
    <view class="growth-records">
      <view class="section-header">
        <text class="section-title">生长记录</text>
        <text class="add-record" @tap="addRecord">添加记录</text>
      </view>
      
      <view class="timeline" v-if="records.length > 0">
        <view 
          v-for="(record, index) in records" 
          :key="index"
          class="timeline-item"
          @tap="viewRecordDetail(record._id)"
        >
          <view class="timeline-dot" :class="getHealthClass(record.health_status)"></view>
          <view class="timeline-content">
            <view class="record-header">
              <text class="record-stage">{{ record.growth_stage }}</text>
              <text class="record-date">{{ formatDate(record.record_date) }}</text>
            </view>
            
            <view class="record-data">
              <view class="data-item" v-if="record.height !== undefined">
                <text class="data-label">高度</text>
                <text class="data-value">{{ record.height }}cm</text>
              </view>
              
              <view class="data-item" v-if="record.leaf_count !== undefined">
                <text class="data-label">叶片数</text>
                <text class="data-value">{{ record.leaf_count }}</text>
              </view>
              
              <view class="data-item">
                <text class="data-label">健康状况</text>
                <text class="data-value" :class="getHealthClass(record.health_status)">{{ getHealthText(record.health_status) }}</text>
              </view>
            </view>
            
            <view class="record-actions">
              <view class="action-tag" v-if="record.watering">浇水</view>
              <view class="action-tag" v-if="record.fertilizing">施肥</view>
              <view class="action-tag" v-if="record.pest_control">病虫害防治</view>
            </view>
            
            <view class="record-notes" v-if="record.notes">
              <text>{{ record.notes }}</text>
            </view>
            
            <view class="record-images" v-if="record.images && record.images.length > 0">
              <image 
                v-for="(img, imgIndex) in record.images.slice(0, 3)" 
                :key="imgIndex"
                :src="img"
                mode="aspectFill"
                class="record-image"
              ></image>
              <view class="more-images" v-if="record.images.length > 3">
                <text>+{{ record.images.length - 3 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 无记录提示 -->
      <view class="empty-records" v-else>
        <uni-icons type="info" size="48" color="#e0e0e0"></uni-icons>
        <text>暂无生长记录</text>
        <text>点击"添加记录"按钮记录生长情况</text>
      </view>
      
      <!-- 加载更多记录 -->
      <view class="load-more" v-if="hasMoreRecords && records.length > 0" @tap="loadMoreRecords">
        <text v-if="!isLoadingRecords">加载更多</text>
        <text v-else>加载中...</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
/// <reference types="@dcloudio/types" />
import { ref, reactive, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';

// 获取页面参数
const getPageParams = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  return currentPage.$page?.options || {};
};

// 农作物数据
const crop = ref(null);
const cropId = ref('');

// 生长记录数据
const records = ref([]);
const recordPage = ref(1);
const recordPageSize = ref(10);
const hasMoreRecords = ref(true);
const isLoadingRecords = ref(false);

// 获取农作物详情
const getCropDetail = async () => {
  try {
    const params = getPageParams();
    cropId.value = params.id;
    
    if (!cropId.value) {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
      goBack();
      return;
    }
    
    const { result } = await uniCloud.callFunction({
      name: 'crop',
      data: {
        action: 'get',
        data: {
          id: cropId.value
        }
      }
    });
    
    if (result.code === 200) {
      crop.value = result.data;
      
      // 获取生长记录
      getGrowthRecords();
    } else {
      uni.showToast({
        title: result.msg,
        icon: 'none'
      });
      goBack();
    }
  } catch (error) {
    console.error('获取农作物详情失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
    goBack();
  }
};

// 获取生长记录
const getGrowthRecords = async (loadMore = false) => {
  if (!cropId.value) return;
  
  try {
    isLoadingRecords.value = true;
    
    if (!loadMore) {
      recordPage.value = 1;
      records.value = [];
    }
    
    const { result } = await uniCloud.callFunction({
      name: 'crop-record',
      data: {
        action: 'list',
        data: {
          crop_id: cropId.value,
          page: recordPage.value,
          pageSize: recordPageSize.value
        }
      }
    });
    
    if (result.code === 200) {
      const { list, pagination } = result.data;
      
      if (loadMore) {
        records.value = [...records.value, ...list];
      } else {
        records.value = list;
      }
      
      hasMoreRecords.value = records.value.length < pagination.total;
      
      // 如果有下一页，更新页码
      if (hasMoreRecords.value) {
        recordPage.value++;
      }
    } else {
      uni.showToast({
        title: result.msg,
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取生长记录失败:', error);
    uni.showToast({
      title: '获取记录失败',
      icon: 'none'
    });
  } finally {
    isLoadingRecords.value = false;
  }
};

// 加载更多记录
const loadMoreRecords = () => {
  if (isLoadingRecords.value || !hasMoreRecords.value) return;
  
  recordPage.value++;
  getGrowthRecords(true);
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 编辑农作物
const editCrop = () => {
  uni.navigateTo({
    url: `/pages/crops/edit?id=${cropId.value}`
  });
};

// 添加记录
const addRecord = () => {
  uni.navigateTo({
    url: `/pages/crops/record?crop_id=${cropId.value}`
  });
};

// 查看记录详情
const viewRecordDetail = (recordId) => {
  uni.navigateTo({
    url: `/pages/crops/record?id=${recordId}&crop_id=${cropId.value}`
  });
};

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未设置';
  
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '种植中';
    case 1: return '已收获';
    case 2: return '已废弃';
    default: return '未知';
  }
};

// 获取状态类名
const getStatusClass = (status) => {
  switch (status) {
    case 0: return 'growing';
    case 1: return 'harvested';
    case 2: return 'abandoned';
    default: return '';
  }
};

// 获取健康状况文本
const getHealthText = (health) => {
  switch (health) {
    case 0: return '不佳';
    case 1: return '一般';
    case 2: return '良好';
    case 3: return '优秀';
    default: return '未知';
  }
};

// 获取健康状况类名
const getHealthClass = (health) => {
  switch (health) {
    case 0: return 'health-poor';
    case 1: return 'health-fair';
    case 2: return 'health-good';
    case 3: return 'health-excellent';
    default: return '';
  }
};

// 页面加载时初始化
onMounted(() => {
  getCropDetail();
});

// 页面显示时刷新数据
onShow(() => {
  if (cropId.value) {
    // 如果已经初始化过cropId，直接刷新数据
    getCropDetail();
  }
});
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding-top: 10px; /* 添加顶部内边距 */
}

/* 农作物基本信息 */
.crop-info {
  background-color: #ffffff;
  margin: 0 10px 10px;
  padding: 15px;
  border-radius: 8px;
  position: relative;
}

/* 编辑按钮 */
.edit-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  display: flex;
  align-items: center;
  background-color: rgba(76, 175, 80, 0.1);
  padding: 5px 10px;
  border-radius: 15px;
}

.edit-btn text {
  font-size: 14px;
  color: #4CAF50;
  margin-left: 5px;
}

.crop-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.crop-image {
  width: 100px;
  height: 100px;
  border-radius: 50px;
  overflow: hidden;
  margin-bottom: 15px;
  border: 4px solid rgba(76, 175, 80, 0.1);
}

.crop-image image {
  width: 100%;
  height: 100%;
}

.crop-title {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 10px;
}

.crop-name {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8px;
}

.crop-status {
  padding: 4px 12px;
  border-radius: 15px;
  background-color: rgba(0, 0, 0, 0.05);
}

.crop-status.growing {
  background-color: rgba(76, 175, 80, 0.1);
}

.crop-status.growing text {
  color: #4CAF50;
}

.crop-status.harvested {
  background-color: rgba(255, 152, 0, 0.1);
}

.crop-status.harvested text {
  color: #FF9800;
}

.crop-status.abandoned {
  background-color: rgba(158, 158, 158, 0.1);
}

.crop-status.abandoned text {
  color: #9E9E9E;
}

.crop-status text {
  font-size: 14px;
}

.crop-type {
  font-size: 14px;
  color: #666666;
}

.info-list {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: #666666;
}

.info-value {
  font-size: 14px;
  color: #333333;
}

/* 生长记录 */
.growth-records {
  background-color: #ffffff;
  padding: 15px;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.add-record {
  font-size: 14px;
  color: #4CAF50;
}

.timeline {
  position: relative;
}

.timeline:before {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 9px;
  width: 2px;
  background-color: #e0e0e0;
}

.timeline-item {
  position: relative;
  padding-left: 30px;
  margin-bottom: 20px;
}

.timeline-item:last-child {
  margin-bottom: 0;
}

.timeline-dot {
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  height: 20px;
  border-radius: 10px;
  background-color: #4CAF50;
  z-index: 1;
}

.timeline-dot.health-poor {
  background-color: #F44336;
}

.timeline-dot.health-fair {
  background-color: #FF9800;
}

.timeline-dot.health-good {
  background-color: #4CAF50;
}

.timeline-dot.health-excellent {
  background-color: #2196F3;
}

.timeline-content {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 12px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.record-stage {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.record-date {
  font-size: 14px;
  color: #999999;
}

.record-data {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.data-item {
  margin-right: 15px;
  margin-bottom: 5px;
}

.data-label {
  font-size: 12px;
  color: #999999;
  margin-right: 5px;
}

.data-value {
  font-size: 14px;
  color: #333333;
}

.data-value.health-poor {
  color: #F44336;
}

.data-value.health-fair {
  color: #FF9800;
}

.data-value.health-good {
  color: #4CAF50;
}

.data-value.health-excellent {
  color: #2196F3;
}

.record-actions {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}

.action-tag {
  font-size: 12px;
  color: #ffffff;
  background-color: #4CAF50;
  padding: 2px 8px;
  border-radius: 10px;
  margin-right: 8px;
  margin-bottom: 5px;
}

.record-notes {
  background-color: #ffffff;
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 10px;
}

.record-notes text {
  font-size: 14px;
  color: #666666;
  line-height: 1.4;
}

.record-images {
  display: flex;
  flex-wrap: wrap;
}

.record-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 8px;
}

.more-images {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  background-color: rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-images text {
  font-size: 16px;
  color: #666666;
}

/* 空记录提示 */
.empty-records {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 0;
}

.empty-records .iconfont {
  font-size: 48px;
  color: #e0e0e0;
  margin-bottom: 15px;
}

.empty-records text:nth-child(2) {
  font-size: 16px;
  color: #999999;
  margin-bottom: 5px;
}

.empty-records text:nth-child(3) {
  font-size: 14px;
  color: #999999;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 15px 0;
}

.load-more text {
  font-size: 14px;
  color: #999999;
}

/* 图标样式 */
.iconfont {
  font-family: "iconfont";
}

.icon-back:before {
  content: "\e679";
}

.icon-edit:before {
  content: "\e66e";
}

.icon-empty:before {
  content: "\e6a6";
}
</style> 